<?php

/**
 * Display the teaser of the node (or definition field if kentry node)
 */
function _kentry_fields_html($node, $page=FALSE){
  $variants = '';
  $css = ((drupal_add_css(drupal_get_path('module', 'kentry').'/kentry.css')));
  unset($css['all']['theme']);
  $output = "";

  if(is_array($node->chn)){
    foreach($node->chn as $kfid=>$values){
      $val = _kfield_view($values, $page, $node);
      if(trim($val) &&
         ($values->kfid != variable_get('xspf_'.$node->type.'_thumb', ''))) {
        $variants.= '<div class="kfield" title="'.check_plain($values->label).'">'.
                    '<label>'.(in_array($values->ftype, array('url'))?'':t($values->label)).' </label>'.
                    '<span itemprop="'.$values->name.'" class="'.$values->name.'">'.$val.'</span>'.
                    '</div>';
      }
    }
  }
  $output.= $variants;
  return $output;
}

/**
 *Format the field object for viewing
 *The $teaser indicates whether the field is being viewed as part of a teaser
 */
function _kfield_view($field, $page=FALSE, $node=NULL){
  $field = (object)$field;
  $type = $field->ftype;
  $value = $field->value;
  switch ($type) {
    case 'textarea':
      return check_markup($value);
    case 'textfield':
      return check_plain($value);
    case 'select':
    case 'list':
      $available = db_result(db_query("SELECT options FROM {kentry_fields}
                                       WHERE kfid=%d", $field->kfid));
      $options = array_map('trim', mb_split("[\n]", $available));
      if($type == 'select'){
        $value = $options[$value];
      }else {
        $picked = array();
        if(is_array($selected = unserialize($value))) {
          foreach($selected as $i){
            $picked[$i] = $options[$i];
          }
        }
        $value = join(', ', $picked);
      }
      return check_plain($value);
    case 'checkbox':
      return check_plain($value);
    case 'url':
      return $value?'<a href="'. check_url($value) .'" target="url">'. check_plain($field->label) .'</a>':'';
    case 'hidden':
      return; # No output
    case 'date':
    case 'datetime':
      if($type != 'datetime') {
        $format = substr(variable_get('date_format_short', 'm/d/Y - H:i'), 0, 5);
      }else {
        $format = variable_get('date_format_short', 'm/d/Y - H:i');
      }
      return $value?format_date($value, 'custom', $format):'';
    case 'list':
      $values = mb_split("[,\n\r]", $value);
      $fields = array();
      foreach ($values as $value) {
        if($value = trim($value)) {
          $fields[] = $browse ? l($value, 'kfield/'. $field->name .'/'. $value) : check_plain($value);
        }
      }
      return implode(', ', $fields);
    case 'isbn': 
      if(trim($value)) {
        return $value.'<script type="text/javascript" src="http://books.google.com/books/previewlib.js"></script>
               <script type="text/javascript">GBS_insertPreviewButtonPopup(\'ISBN:'.$value.'\');</script>';
      }else {# no output if there's no ISBN
        return;
      }
    case 'place':
      if(trim($value)) {
        return $value;
      }else {
        return;
      } 
    case 'map':
      $geo = unserialize($value);
      if(@array_filter($geo)) {
        return '<span class=".map"><div id="map'.$node->nid.'"></div>'.
               _kentry_insert_map($node, 'map'.$node->nid).'</span>';
      }else { return; }
    case 'price':
      $price = unserialize($value);
      if(array_filter($price)) {
        return t('@curr @amt', array('@curr' => $price['curr'], '@amt' => $price['amt']));
      }else {return; }
    case 'range':
      $range = unserialize($value);
      if(array_filter($range)) {
        return t('From @low to @high @unit', array('@low' => $range['min'], '@high' => $range['max'], '@unit' => $range['unit']));
      }else {return; }
    }
}

function _kfield_handler($field){
  $handler = new StdClass();
  $options = array();
  $special = array('url', 'isbn', 'place', 'hidden');
  if(in_array($field->ftype, $special)) {
    $field->ftype='textfield';
  }
  if(in_array($field->ftype, array('date', 'datetime'))) {
    $field->value = array('day'=>date('j', $field->value),
                          'month'=>date('n', $field->value),
                          'year'=>date('Y', $field->value),
                          'hour'=>date('G', $r->value),
                          'minute'=>date('i', $r->value)
    );
  }else if(in_array($field->ftype, array('select', 'list'))){
    $available = db_result(db_query("SELECT options FROM {kentry_fields}
                                     WHERE kfid=%d", $field->kfid));
    $options = array(
      '#options' => array_map('trim', mb_split("[\n]", $available)),
      '#multiple' => $field->ftype=='list'?1:0
    );
    $field->ftype = 'select';
    if($options['#multiple']) {
      $field->value = unserialize($field->value);
    }
  }else if(in_array($field->ftype, array('map', 'price', 'range'))) {
    switch($field->ftype) {
      case 'map':
        $field->kfields = array('place' => '', 'lat' => '', 'long' => '', 'elev' => 0);
        break;
      case 'price':
        $field->kfields = array('curr' => '', 'amt' => '');
        break;
      case 'range':
        $field->kfields = array('min' => '', 'max' => '', 'unit' => '');
        break;
    }
    $field->ftype = 'multitextfield';
    $field->value = unserialize($field->value);
  }

  if(trim($field->link)) {
    list($db, $rel) = mb_split('\|', $field->link);
    $linkinfo = t('Comma-separated entries in this field will be looked up '.
                  'in the %db database to generate %link options for '.
                  'confirmation !here. ',
                  array('%db' => _name($db),
                        '%link' => variable_get('ksynset_'.trim($rel).'_name', ''),
                        '!here'=>l(t('here'), "node/$field->nid/relations"))
                 );
  }

  $handler->form = array_merge($options, 
    array(
      '#type'=>$field->ftype,
      '#description'=>$linkinfo.$field->explanation,
      '#title'=>$field->label,
      '#default_value'=>$field->value,
      '#kfields' => $field->kfields, # custom fields
    ));
    return $handler;
}

/**
 * Add a map visualization here if the node has a geo-point
 */
function _kentry_insert_map($node, $div) {
  global $user;
  $output = '';
  $height = 300; # in px
  $width = 100; # in percent
  $thumb_width = 1.5 * $width * $height/100; # in px
  $title = str_replace("'", "&#039;", $node->title);
  if($node->geopoint) {
    $mapspan = 1; 
    $latlong = $node->geopoint;
    $params = array();
    #required
    $params[] = 'size='.$thumb_width.'x'.$height;
    $params[] = 'sensor=false';
    #$params[] = 'center='.$latlong;
    $params[] = 'span='.$mapspan;
    #optional
    $params[] = "hl=$user->language";
    $params[] = 'maptype=hybrid';
    $params[] = "markers=color:yellow|$latlong";
    $query = join("&", $params);
    $thumb = "http://maps.google.com/maps/api/staticmap?$query";

    $map_js = variable_get('kmap_js_include', 'http://api.fienipa.com/map.js');
    $zoomable = <<<ZOOM
<script type="text/javascript"><!--
var kmap_center_lat =  $node->latitude;
var kmap_center_long = $node->longitude;
var kmap_type = 'roadmap';
var kmap_div = '$div';
var kmap_zoom = 2;
var kmap_title = '$title';
var obj= document.getElementById('$div');
obj.style.height = '$height'+'px';
//--></script>
<script src="$map_js"></script>
<noscript><img src='$thumb' alt='Map' class='map' title='$title' /></noscript>
ZOOM;
      drupal_set_html_head("<style>#map$node->nid {width: ".$width."%;} .map {".
              "text-align: center;".
              "height:".($height)."px; ".
              "width:".($thumb_width)."px; ".
              "margin:0 auto;}".
              "</style>");
       $output.= $zoomable;
    }
  return $output;
}
